package cn.fboost.mtos.service.impl;

import cn.fboost.mtos.dto.Response;
import cn.fboost.mtos.dto.internal.Session;
import cn.fboost.mtos.dto.request.*;
import cn.fboost.mtos.dto.response.PageResponse;
import cn.fboost.mtos.entity.Product;
import cn.fboost.mtos.mapper.CategoryMapper;
import cn.fboost.mtos.mapper.ProductMapper;
import cn.fboost.mtos.mapper.ProductRateMapper;
import cn.fboost.mtos.service.ProductService;
import cn.fboost.mtos.util.ContextHolderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {
    private final ProductMapper productMapper;
    private final CategoryMapper categoryMapper;
    private final ProductRateMapper productRateMapper;

    public ProductServiceImpl(ProductMapper productMapper, CategoryMapper categoryMapper, ProductRateMapper productRateMapper) {
        this.productMapper = productMapper;
        this.categoryMapper = categoryMapper;
        this.productRateMapper = productRateMapper;
    }

    @Override
    public Response listByCategory(ProductListByCategoryRequest request) {
        List<Product> list = productMapper.listByCategoryId(request.getCategoryId(),
                request.getPagination().getPageOffset());

        return Response.builder().success()
                .msg("获取成功")
                .data(list)
                .build();
    }

    @Override
    public Response listByMonthlySales(ProductListByMonthlySalesRequest request) {
        // 对普通用户过滤已下架的商品
        Session session = ContextHolderUtil.getCurrentSession();
        List<Product> list = productMapper.listByMonthlySales(request.getSize(),
                session == null || session.getRole() == Session.Role.USER);
        return Response.builder().success()
                .msg("获取成功")
                .data(list)
                .build();
    }

    @Override
    public Response detail(Integer id) {
        Product product = productMapper.findById(id);

        // 普通用户无法查看下架商品的详情
        Session session = ContextHolderUtil.getCurrentSession();
        if ((session == null || session.getRole() == Session.Role.USER) && product.getOffShelf()) {
            return Response.builder().failure().msg("商品已下架").build();
        }

        return Response.builder().success().msg("获取成功").data(product).build();
    }

    @Override
    public Response create(ProductCreateRequest request) {
        if (categoryMapper.findById(request.getCategoryId()) == null) {
            return Response.builder().failure().msg("商品分类不存在").build();
        }

        Product product = new Product();
        product.setCategoryId(request.getCategoryId());
        product.setName(request.getName());
        product.setDescribe(request.getDescribe());
        product.setImage(request.getImage());
        product.setPrice(request.getPrice());
        product.setSellOut(false);
        product.setOffShelf(false);
        product.setRate(0d);
        product.setRateTotal(0);
        product.setSalesMonth(0);
        product.setSalesTotal(0);
        if (productMapper.create(product) == 0) {
            return Response.builder().success().msg("商品添加失败").build();
        }

        return Response.builder().success().msg("商品已添加").build();
    }

    @Override
    public Response update(ProductUpdateRequest request) {
        Product product = productMapper.findById(request.getId());
        if (product == null) {
            return Response.builder().failure().msg("商品不存在").build();
        }

        if (request.getCategoryId() != null && categoryMapper.findById(request.getCategoryId()) == null) {
            return Response.builder().failure().msg("商品分类不存在").build();
        }

        // 创建更新实体
        Product update = new Product();
        update.setId(request.getId());
        update.setCategoryId(request.getCategoryId());
        update.setName(request.getName());
        update.setPrice(request.getPrice());
        update.setImage(request.getImage());
        update.setDescribe(request.getDescribe());
        update.setSellOut(request.getSellOut());
        update.setOffShelf(request.getOffShelf());
        if (productMapper.update(update) == 0) {
            return Response.builder().failure().msg("商品更新失败").build();
        }

        return Response.builder().success().msg("商品已更新").build();
    }

    @Override
    public Response delete(ProductDeleteRequest request) {
        if (productMapper.deleteById(request.getId()) == 0) {
            return Response.builder().failure().msg("商品删除失败").build();
        }

        return Response.builder().success().msg("商品已删除").build();
    }

    @Override
    public Response count() {
        return Response.builder().msg("获取成功").data(productMapper.count()).build();
    }

    @Override
    public Response list(PageRequest request) {
        int total = productMapper.count();
        List<Product> list = productMapper.list(request.getPageOffset());

        PageResponse resp = new PageResponse();
        resp.setTotal(total);
        resp.setList(list);
        return Response.builder().success().msg("获取成功").data(resp).build();
    }

    @Override
    public Response getComments(Integer id) {
        // 读取最近30条评分
        PageRequest pageRequest = new PageRequest();
        pageRequest.setPage(1);
        pageRequest.setSize(30);

        return Response.builder().success()
                .data(productRateMapper.listByProductId(id, pageRequest.getPageOffset()))
                .build();
    }
}
